<?php
	session_start(); 

/*™*******************************************************************************************™*/
	
	// include script
	require("./inc/config-system.inc.php");	
	require("./inc/config-db.inc.php");
	require("./inc/fm.inc.php");
	require("./class/adodb/adodb.inc.php");
	require("./class/validate/validate.inc.php");

/*™*******************************************************************************************™*/
	
	// validate data input
    
    // set rule for each input field
    $position = 0;
    $inputLabel[] = "Document Date";
    $ruleElement["TXTdoc_date"][0] = array
        (
            "checkNotEmpty" => $inputLabel[$position]
        );	
            
    // validate rule header                                          
    $errorMessageJSON = validateElementAdminAccount($ruleElement, 0); // see in fm.inc.php
    
    if (!empty($errorMessageJSON)) {
        echo $errorMessageJSON; // return json format
        exit();
    } else {
        $inputLabel = array();
        $ruleElement = array();
        $position = 0;
    }      

    // validate rule item                                          
	for ($index = 0; $index <= (int) $_POST["HIDnum_row"]; $index++) {	 
      
		$position = 0;
		$inputLabel[] = "PK";
		$ruleElement["SELpk"][$index] = array
			(
				"checkNotSelect" => $inputLabel[$position]
			);
	
		$position = $position + 1;
		$inputLabel[] = "Account";
		$ruleElement["TXTgl_account"][$index] = array
			(
				"checkNotEmpty" => $inputLabel[$position]
			);
	
		
		$position = $position + 1;
		$inputLabel[] = "Description";
		$ruleElement["TXTdescription"][$index] = array
			(
				"checkNotEmpty" => $inputLabel[$position]
			);
	
/*		$position = $position + 1;
		$inputLabel[] = "Quantity";
		$ruleElement["TXTquantity"][$index] = array
			(
				"checkNotEmpty" => $inputLabel[$position],
				"checkIsCurrency" => $inputLabel[$position]
			);
	
		$position = $position + 1;
		$inputLabel[] = "Price / Unit";
		$ruleElement["TXTprice_unit"][$index] = array
			(
				"checkNotEmpty" => $inputLabel[$position],
				"checkIsCurrency" => $inputLabel[$position]
			);
*/	

        // validate rule                                            
        $errorMessageJSON = validateElementAdminAccount($ruleElement, $index); // see in fm.inc.php
        
        if (!empty($errorMessageJSON)) {
            echo $errorMessageJSON; // return json format
            exit();
        } else {
            $inputLabel = array();
            $ruleElement = array();
            $position = 0;
        }

	}

/*™*******************************************************************************************™*/

	// add data into database
	
	$adj_total_amount = 0;
	
	// connection database
	$objConn = ADONewConnection(DB_DRIVER); 
	$objConn->Connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
	//$objConn->debug = TRUE;

	// get running no.
	$sqlCommand = "SELECT * FROM tbl_runing_doc WHERE run_type = 'AD' LIMIT 1";  
	$recordset = $objConn->Execute($sqlCommand);
	while (!$recordset->EOF) {
		$run_no = $recordset->fields["run_no"];
		$recordset->MoveNext();
	}

	// insert item in adj document
    for ($index = 0; $index <= (int) $_POST["HIDnum_row"]; $index++) {    
        
	    // execute the query and get empty recordset
	    $sqlCommand = "SELECT * FROM tbl_adj WHERE adj_id = -1";  
	    $recordset = $objConn->Execute($sqlCommand);
	    
	    // record data to insert
	    $record = array(); 

	    $record["adj_docdate"] = $_POST["TXTdoc_date"][0]; 
	    $record["adj_postkey"] = $_POST["SELpk"][$index]; 
	    $record["adj_account"] = $_POST["TXTgl_account"][$index]; 
	    $record["adj_description"] = $_POST["TXTdescription"][$index]; 
	    $record["adj_quantity"] = $_POST["TXTquantity"][$index]; 
	    $record["adj_price_unit"] = $_POST["TXTprice_unit"][$index]; 
		
		if ( (isset($_POST["TXTquantity"][$index]) && $_POST["TXTquantity"][$index] != "") && 
			 (isset($_POST["TXTprice_unit"][$index]) && $_POST["TXTprice_unit"][$index] != "")) { // have quantity and price:unit
	    	$record["adj_amount"] = $_POST["TXTquantity"][$index] * $_POST["TXTprice_unit"][$index];
		} else { // have amount only
			if ($_POST["SELpk"][$index] == "02") {
	    		$record["adj_amount"] = $_POST["TXTamount"][$index] * -1; // ไม่เอาเครื่องหมาย - ถ้าน้อยกว่า 0 ตอนลง db
			} else {
				$record["adj_amount"] = $_POST["TXTamount"][$index];
			}
		}
		
	    $record["adj_docno"] = $run_no; 
	    
	    $record["created_date"] = time(); 
	    $record["modified_date"] = time(); 
	    
		if ($_POST["TXTtotal_amount"] == 0 && isset($_POST["BTTpost"])) { // adj balance post to database
			// generating insert sql
			$sqlCommand = $objConn->GetInsertSQL($recordset, $record);
			
			// insert the record into database
			$objConn->Execute($sqlCommand); 
	
			// returns the last auto numbering ID inserted
			//$auto_id = $objConn->Insert_ID();
		}
		
		// calc. amount for show
		if ($index == 0) {
			echo "{";
		}
		
		
		// GL 1 or 2 or 3 or 4 or 5
		if (substr($_POST["TXTgl_account"][$index], 0, 1) == "1" || 
			substr($_POST["TXTgl_account"][$index], 0, 1) == "2" ||
			substr($_POST["TXTgl_account"][$index], 0, 1) == "3" ||
			substr($_POST["TXTgl_account"][$index], 0, 1) == "4" ||
			substr($_POST["TXTgl_account"][$index], 0, 1) == "5") {
			
			if ($_POST["SELpk"][$index] == "01") {
				if ($record["adj_amount"] < 0) {
					$record["adj_amount"] = $record["adj_amount"] * -1; // ถ้าช่อง amount pk 02 ติดลบมาจากการคำนวณ ให้ทำให้กลายเป็น +
				}
				$record["adj_amount"] = $record["adj_amount"];
			} elseif ($_POST["SELpk"][$index] == "02") {
				if ($record["adj_amount"] < 0) {
					$record["adj_amount"] = $record["adj_amount"] * -1; // ถ้าช่อง amount pk 02 ติดลบมาจากการคำนวณ ให้ทำให้กลายเป็น +
				}
				$record["adj_amount"] = $record["adj_amount"] * -1;
			}
						
		}
		
		// show amount in textbox do not show sign -  
/*		$adj_amount_show = "";
		
		if ($record["adj_amount"] < 0) {
			$adj_amount_show = $record["adj_amount"] * -1;	
		} else {
			$adj_amount_show = $record["adj_amount"];	
		}
*/		
		//echo "'TXTamount_" . $index . "':'" . $adj_amount_show . "',\n";
		echo "'TXTamount_" . $index . "':'" . $record["adj_amount"] . "',\n";

		//$adj_total_amount = $adj_total_amount + $record["adj_amount"]; // !!! bug ถึงจะเอาเลขมาลบกันแล้วได้ 0 แต่เพราะอะไรไม่รู้มันได้ไม่เป็น 0 แต่ได้เป็น 8.881784197E-16!!!
		$adj_total_amount = (string) $adj_total_amount + (string) $record["adj_amount"]; // !!! fix bug must convert to string before + !!!

	}
	
	echo "'TXTtotal_amount':'" . $adj_total_amount . "',\n";
	
	if ($_POST["TXTtotal_amount"] == 0 && isset($_POST["BTTpost"])) {  // adj balance get running no.
		// update runing no.
		$sqlCommand = "SELECT * FROM tbl_runing_doc WHERE run_type = 'AD'";  
		$recordset = $objConn->Execute($sqlCommand);
	
		// record data to update
		$record = array(); 
	
		$record["run_no"] = $run_no + 1; 
		
		$record["created_date"] = time(); 
		$record["modified_date"] = time(); 
		
		// generating update sql
		$sqlCommand = $objConn->GetUpdateSQL($recordset, $record);
		
		// update the record into database
		$objConn->Execute($sqlCommand); 
	}
	
/*™*******************************************************************************************™*/
	
	// return json format
	$location = "./adj_form.php";
	
	if ($adj_total_amount == 0 && isset($_POST["BTTpost"])) {  // adj balance
		echo "'POSTING_SUCCESS':'Posting ADJUST Document No. " . $run_no . " was create',\n";
		echo "'POSTING_REDIRECT':'" . urlencode($location) . "'\n";
		echo "}";
		exit();
	} elseif ($adj_total_amount == 0 && isset($_POST["BTTsimulate"])) {
		echo "'SIMULATE_SUCCESS':'Simulate ADJUST Document BALANCE',\n";
		echo "}";
		exit();
	} else {
		echo "'SIMULATE_FAIL':'!!! Simulate ADJUST Document NOT BALANCE !!!',\n";
		echo "}";
		exit();
	}
	
/*™*******************************************************************************************™*/
?>